package Server.Init;

import Library.Common.Message;
import Library.Model.User;
import Server.Commands.CommandFactory;
import Server.Commands.CommandServer;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class ServerThread extends Thread {

    private Socket clientSocket;
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private User user;
    private Boolean userActive;

    public ServerThread(Socket clientSocket) {
        this.clientSocket = clientSocket;
        this.userActive = true;
    }

    @Override
    public void run() {
        try {
            output = new ObjectOutputStream(clientSocket.getOutputStream());
            input = new ObjectInputStream(clientSocket.getInputStream());
            while(userActive){
                Message message = (Message) input.readObject();
                CommandServer command = CommandFactory.getCommandServer(message.getMessage());
                command.execute();
            }
        } catch (IOException | ClassNotFoundException ex) {
            ex.printStackTrace();
        } finally{
            if(clientSocket!=null){
                try {
                    clientSocket.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    
    
    

}
